﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;

namespace DtuService
{
    static class Program
    {
        //计时器变量
        public static System.Threading.Timer workOvertimeTimer = null;
        public static int StartAppType = 0;
        private static System.Timers.Timer timer;
        private static string watchExeName = "DtuService.exe";

        static void CreateConsoleHook()
        {

            ConsoleCtrlDelegate newDelegate = new ConsoleCtrlDelegate(HandlerRoutine);
            if (Win32Helper.SetConsoleCtrlHandler(newDelegate, true))
            {
                while (true)
                {
                    // 主进程循环
                    ServerMain.Instance.ServerRun();
                    Thread.Sleep(1);
                }
            }
            else
            {
                Console.WriteLine("抱歉，API注入失败，按任意键退出！");
                Console.ReadKey();
            }
        }
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);

            //Process instance = RunningInstance();
            //if (instance != null)
            //{
            //    HandleRunningInstance(instance);
            //    return;
            //}
            try
            {
                //HideConsole();
                Console.ForegroundColor = ConsoleColor.DarkYellow;
                StartAppType = args.Length != 0 ? int.Parse(args[0]) : 0;
                if (StartAppType == 0)
                {
                    startServer();
                    CreateConsoleHook();
                }
                else
                {
                    startWatchServer();
                    HideConsole();
                    while (true)
                    {
                        Thread.Sleep(1);
                    }
                }
               
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
        }

        private static void startServer()
        {
            Console.WriteLine("服务器启动");
            ServerMain.Instance.StartServer();
            Console.WriteLine("启动守护进程");
#if !DEBUG
            startWatchServer();
#endif
        }

        private static void startWatchServer()
        {
            timer = new System.Timers.Timer(1000);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;
            timer.AutoReset = true;
            timer.Start();
        }

        /// <summary>  
        /// 隐藏控制台  
        /// </summary>  
        /// <param name="ConsoleTitle">控制台标题(可为空,为空则取默认值)</param>  
        public static void HideConsole(string ConsoleTitle = "")
        {
            ConsoleTitle = String.IsNullOrEmpty(ConsoleTitle) ? Console.Title : ConsoleTitle;
            IntPtr hWnd = Win32Helper.FindWindow("ConsoleWindowClass", ConsoleTitle);
            if (hWnd != IntPtr.Zero)
            {
                Win32Helper.ShowWindow(hWnd, 0);
            }
        }

        /// <summary>
        /// 处理程序例程，在这里编写对指定事件的处理程序代码
        /// </summary>
        /// <param name="CtrlType"></param>
        /// <returns></returns>
        public static bool HandlerRoutine(int CtrlType)
        {
            switch (CtrlType)
            {
                case Win32Helper.CTRL_CLOSE_EVENT:       //用户要关闭Console了
                    Console.WriteLine();
                    ServerMain.Instance.ShutdownServer();
                    return false;
                default:
                    return true;
            }
        }

        static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            watchExeName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
            Process[] p = Process.GetProcessesByName(watchExeName);

            if (p.Length == 1)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.Gray;
                string param = StartAppType == 0 ? "1" : "0";
                System.Diagnostics.Process proc = System.Diagnostics.Process.Start(watchExeName + ".exe", param);
            }
        }

#region  确保程序只运行一个实例
        private static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历与当前进程名称相同的进程列表 
            foreach (Process process in processes)
            {
                //如果实例已经存在则忽略当前进程 
                if (process.Id != current.Id)
                {
                    //保证要打开的进程同已经存在的进程来自同一文件路径
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        //返回已经存在的进程
                        return process;
                    }
                }
            }
            return null;
        }

        private static void HandleRunningInstance(Process instance)
        {
            MessageBox.Show("已经在运行！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Win32Helper.ShowWindowAsync(instance.MainWindowHandle, 1);  //调用api函数，正常显示窗口
            Win32Helper.SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
            Application.Exit();
        }
#endregion
    }
}
